package com.example.emailcraft.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.emailcraft.entity.UserTemplates;
import com.example.emailcraft.entity.common.Result;
import com.example.emailcraft.entity.request.CheckExportPermissionRequest;
import com.example.emailcraft.entity.request.SaveTemplateRequest;
import com.example.emailcraft.entity.response.SaveTemplateResponse;
import com.example.emailcraft.handler.GlobalExceptionHandler;
import com.example.emailcraft.interceptor.CurrentUserHolder;
import com.example.emailcraft.mapper.UserTemplatesMapper;
import com.example.emailcraft.service.IUserTemplatesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author scj
 * @since 2025-01-21
 */
@Service
@Slf4j
public class UserTemplatesServiceImpl extends ServiceImpl<UserTemplatesMapper, UserTemplates> implements IUserTemplatesService {
    @Autowired
    private UserTemplatesMapper userTemplatesMapper;

    @Override
    @Transactional
    public ResponseEntity<Result<Object>> saveTemplate(SaveTemplateRequest request) {
        try {
            // 1. 检查必填字段是否为空
            if (request.getTitle() == null || request.getTitle().isEmpty()) {
                throw new GlobalExceptionHandler.BusinessException(
                        GlobalExceptionHandler.ErrorCode.BAD_REQUEST,
                        "模板标题不能为空"
                );
            }
            if (request.getContent() == null || request.getContent().isEmpty()) {
                throw new GlobalExceptionHandler.BusinessException(
                        GlobalExceptionHandler.ErrorCode.BAD_REQUEST,
                        "模板内容不能为空"
                );
            }
            // 1. 获取当前用户ID
            Integer userId = Math.toIntExact(CurrentUserHolder.getRequired().getUserId());
            log.info("当前用户ID: {}", userId);

            // 2. 创建模板对象
            UserTemplates template = new UserTemplates();
            template.setUserId(userId);
            template.setTitle(request.getTitle());
            template.setContent(request.getContent());
            template.setCategoryId(request.getCategoryId());
            template.setCreatedAt(LocalDateTime.now());
            template.setUpdatedAt(LocalDateTime.now());

            // 3. 保存模板到数据库
            userTemplatesMapper.UserTemplatesInsert(template);

            // 4. 返回成功响应
            return ResponseEntity.ok(
                    new Result<>().setCode(HttpStatus.OK.value()).setMessage("保存模板成功").setData(new SaveTemplateResponse())
            );
        } catch (Exception e) {
            // 5. 抛出业务异常
            throw new GlobalExceptionHandler.BusinessException(GlobalExceptionHandler.ErrorCode.INTERNAL_SERVER_ERROR, "保存模板失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<Result<Object>> checkExportPermission() {
        try {
            // 1. 获取当前用户ID和角色
            Integer userId = Math.toIntExact(CurrentUserHolder.getRequired().getUserId());
            String roles = CurrentUserHolder.getRequired().getRoles();
            CheckExportPermissionRequest request = new CheckExportPermissionRequest();
            // 2. 检查用户是否有导出权限
            boolean hasPermission = roles.contains("user"); // 假设只有 ADMIN 角色有导出权限

            // 3. 返回响应
            if (hasPermission) {
                request.setIsExport(true);
                request.setUserId(userId);
                return ResponseEntity.ok(
                        new Result<>().setCode(HttpStatus.OK.value()).setMessage("有权限导出模板")
                        .setData(request)
                );
            } else {
                throw new GlobalExceptionHandler.BusinessException(GlobalExceptionHandler.ErrorCode.FORBIDDEN, "无权限导出模板");
            }
        } catch (Exception e) {
            // 4. 抛出业务异常
            throw new GlobalExceptionHandler.BusinessException(GlobalExceptionHandler.ErrorCode.INTERNAL_SERVER_ERROR, "检查权限失败：" + e.getMessage());
        }
    }
}
